package com.zdp.oauth2.server.service;

import com.zdp.commons.model.domain.SignInIdentity;
import com.zdp.commons.model.pojo.Diners;
import com.zdp.commons.utils.AssertUtil;
import com.zdp.oauth2.server.mapper.DinersMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author sesshomaru
 * @date 2021/6/6 15:28
 */
@Service
public class UserService implements UserDetailsService {

    @Resource
    private DinersMapper dinersMapper;

    /**
     * 根据用户名获取用户信息，为啥不要密码呢？用户登录肯定是有用户名和密码的，先通过用户名去数据库把密码拿出来，然后security
     * 帮着去做密码的校验如果通过就会给用户生成令牌
     * @param username 用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        AssertUtil.isNotEmpty(username, "请输入用户名");
        Diners diners = dinersMapper.selectByAccountInfo(username);
        if (diners == null) {
            throw new UsernameNotFoundException("用户名或密码错误，请重新输入");
        }
        // 基础版
        /*return new User(username,
                // 密码
                diners.getPassword(),
                // 角色
                AuthorityUtils.commaSeparatedStringToAuthorityList(diners.getRoles()));*/

        // 增强版自定义登录认证对象
        // 初始化登录认证对象
        SignInIdentity signInIdentity = new SignInIdentity();
        // 拷贝属性
        BeanUtils.copyProperties(diners, signInIdentity);
        return signInIdentity;
    }
}
